package com.shangyueshang.handlers;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2021/7/20 20:07
 * @version: v1.0.0
 */
@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringTypeHandler extends AbstractJsonTypeHandler<List<String>> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @SneakyThrows
    @Override
    protected List<String> parse(String json) {
        if (!StringUtils.hasText(json)) {
            return Collections.emptyList();
        }
        return MAPPER.readValue(json, new TypeReference<List<String>>() {
        });
    }

    @SneakyThrows
    @Override
    protected String toJson(List<String> obj) {
        if (obj == null) {
            return "[]";
        }
        return MAPPER.writeValueAsString(obj);
    }
}
